package org.example.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.example.entity.AuthCode;
import org.example.repository.AuthCodeRepository;
import org.example.service.CodeService;
import org.example.service.EmailService;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class CodeServiceImpl implements CodeService {

    private final AuthCodeRepository authCodeRepository;

    @Reference
    private EmailService emailService;

    @Override
    public Boolean create(String email) {
        String code = RandomUtils.nextInt(899999)+100000+"";
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        authCode.setCreatetime(LocalDateTime.now());
        authCode.setExpiretime(LocalDateTime.now().plusMinutes(5));
        AuthCode save = authCodeRepository.save(authCode);
        log.info("当前时间： {}", LocalDateTime.now());
        if (emailService.send(email, code)){
            return true;
        }
        log.info("当前时间： {}", LocalDateTime.now());
        Integer id = save.getId();
        authCodeRepository.deleteById(id);
        return false;
    }

    @Override
    public int validate(String email, String code) {
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        Example<AuthCode> example = Example.of(authCode);
        List<AuthCode> allAuthCodes = authCodeRepository.findAll(example);
        if (allAuthCodes.size() > 0){
            allAuthCodes.sort((a,b)->b.getExpiretime().compareTo(a.getExpiretime()));
            AuthCode authCode1 = allAuthCodes.get(0);
            boolean before = LocalDateTime.now().isBefore(authCode1.getExpiretime());
            if (before){
                return 0;
            }
            return 2;
        }
        return 1;
    }
}
